package com.cci.zkweb.core.entity;

import java.util.HashSet;
import java.util.Set;

import javax.security.auth.Subject;

import com.cci.zkweb.core.services.P8Service;
import com.cci.zkweb.core.services.impl.P8ServiceImpl;
import com.cci.zkweb.core.util.ZKFUtils;
import com.filenet.api.util.UserContext;

public class SessionItem {
	private User currentUser;
	private P8Service p8Service;
	private Set<String> roles = new HashSet<String>();

	public SessionItem(User user, String password) {
		this.currentUser = user;
		this.p8Service = new P8ServiceImpl();
		initSessionItem(password);
	}
	
	public SessionItem() {
		roles.add(ZKFUtils.ANONYMOUS);
		currentUser = null;
	}

	public void initSessionItem(String password) {
		System.setProperty(
				"java.security.auth.login.config",
				"C:/Progetti/Programmi/servers/ZKFilenet/security/jaas.conf.WSI");
		
		if(currentUser == null) return;
		Subject subject = UserContext.createSubject(
				this.p8Service.getConnection(), 
				this.currentUser.getAccount(), 
				password, 
				"FileNetP8WSI");
		this.p8Service.LoginToServiceContext(subject);
	}
	
	public P8Service getP8Service() {
		return this.p8Service;
	}
	
	public boolean getAnonymous() { return isAnonymous(); }
	public boolean isAnonymous() {
		return hasRole(ZKFUtils.ANONYMOUS) || this.currentUser == null;
	}
	
	public String getName() {
		return currentUser != null ? currentUser.getFullName() : ZKFUtils.ANONYMOUS;
	}
	
	public String getUserMail() {
		return currentUser != null ? currentUser.getEmail() : "[NO MAIL]";
	}
	
	public boolean hasRole(String role){
		return roles.contains(role);
	}

	public void addRole(String role){
		roles.add(role);
	}
	
	public void destroy() {
		UserContext.get().popSubject();
	}
}
